package cn.tedu.ivos.geofence.service.Impl;

import cn.tedu.ivos.base.exception.ServiceException;
import cn.tedu.ivos.base.response.StatusCode;
import cn.tedu.ivos.geofence.mapper.GeofenceMapper;
import cn.tedu.ivos.geofence.pojo.dto.GeofenceParam;
import cn.tedu.ivos.geofence.pojo.dto.GeofenceQuery;
import cn.tedu.ivos.geofence.pojo.entity.Geofence;
import cn.tedu.ivos.geofence.pojo.vo.GeofenceVO;
import cn.tedu.ivos.geofence.service.GeofenceService;
import cn.tedu.ivos.vehicle.mapper.VehicleMapper;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleQuery;
import cn.tedu.ivos.vehicle.pojo.vo.VehicleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class GeofenceServiceImpl implements GeofenceService {
    @Autowired
    GeofenceMapper geofenceMapper;

    @Autowired
    VehicleMapper vehicleMapper;

    @Override
    public List<GeofenceVO> selectGeoFence(GeofenceQuery geofenceQuery) {
        log.debug("查询围栏信息业务:geofenceQuery={}",geofenceQuery);
        List<GeofenceVO> list = geofenceMapper.selectGeofence(geofenceQuery);
        return list;
    }

    @Override
    public void saveGeofence(GeofenceParam geofenceParam) {
        log.debug("保存围栏信息业务:geofenceParam={}",geofenceParam);
        Geofence geofence = new Geofence();
        BeanUtils.copyProperties(geofenceParam,geofence);
        if(geofence.getId()!=null){
            geofence.setUpdateTime(new Date());
            geofenceMapper.update(geofence);
        }else{
            geofence.setStatus("1");
            geofence.setCreateTime(new Date());
            geofenceMapper.insert(geofence);
        }
    }

    @Override
    public void deleteGeofence(Long id) {
        log.debug("删除围栏信息业务：id={}",id);
        //业务：需要判断该围栏是否有绑定车辆，如果有，不能删除
        //1.封装车辆查询的DTO层对象
        VehicleQuery vehicleQuery = new VehicleQuery();
        vehicleQuery.setGeofenceId(id);
        //2.调用车辆查询接口查询该围栏下的车辆列表
        List<VehicleVO> vehicleVOS = vehicleMapper.selectVehicle(vehicleQuery);
        //3.如果该围栏有车辆，业务层需要抛出操作失败的异常
        if(vehicleVOS.size()>0 && vehicleVOS !=null){
            throw new ServiceException(StatusCode.OPERATION_FAILED);
        }else{
            //4.如果该围栏下没有车辆，可以正常删除
            geofenceMapper.deleteGeofence(id);
        }


    }
}
